//
//  ChangeCommitViewController.m
//  GYMWinners
//
//  Created by Martin Ma on 12-06-14.
//  Copyright (c) 2012 AJB Software Design Inc. All rights reserved.
//

#import "ChangeCommitViewController.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJSON.h"
#import "MBProgressHUD.h"
#import "BaseroutAPI.h"
#import "AppDelegate.h"

static int current_tag = 0;
static int current_row = 0;

@implementation ChangeCommitViewController
@synthesize thisCommitDays;
@synthesize thisCommitPenalty;
@synthesize commitDays;
@synthesize commitPenalty;
@synthesize actionSheet;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self UpdateGUIThisWeekText ];
    
    [self UpdateGUIText];

}

- (void) UpdateGUIThisWeekText
{

    NSString *scommitid = [[BaseroutAPI sharedInstance] zGetVar:@"currentCommitID"];
    NSInteger icommitid = [scommitid intValue];
    
    NSArray *commitsArr = (NSArray *)[[BaseroutAPI sharedInstance] zGetObj:@"commitsArr"];
    NSDictionary *tmp = [commitsArr objectAtIndex:icommitid-1];
    thisCommitDays.text = [NSString stringWithFormat:@"每周出勤                     %@天", [tmp objectForKey:@"commits"]];
    
    NSString *sstakeid = [[BaseroutAPI sharedInstance] zGetVar:@"currentStakeID"];
    NSInteger istakeid = [sstakeid intValue];
    
    NSArray *stakesArr = (NSArray *)[[BaseroutAPI sharedInstance] zGetObj:@"stakesArr"];
    tmp = [stakesArr objectAtIndex:istakeid-1];
    NSString *tmp2 = [tmp objectForKey:@"stakes"];
    NSInteger ii = [tmp2 intValue];
    thisCommitPenalty.text = [NSString stringWithFormat:@"缺勤每次罚金             %2d元", ii];
    
}
- (void) UpdateGUIText
{
    
    NSLog(@"UpdateGUIText SelectedCommitID=%@, SelectedStakeID=%@", [[BaseroutAPI sharedInstance] zGetVarEx:@"selectedCommitID"], [[BaseroutAPI sharedInstance] zGetVarEx:@"selectedStakeID"]);
    
    NSString *scommitid = [[BaseroutAPI sharedInstance] zGetVar:@"futureCommitID"];
    NSInteger icommitid = [scommitid intValue];
    
    NSArray *commitsArr = (NSArray *)[[BaseroutAPI sharedInstance] zGetObj:@"commitsArr"];
    NSDictionary *tmp = [commitsArr objectAtIndex:icommitid-1];
    commitDays.text = [NSString stringWithFormat:@"每周出勤                     %@天", [tmp objectForKey:@"commits"]];
    
    NSLog(@"%@", [tmp objectForKey:@"commits"]);
   
    
    NSString *sstakeid = [[BaseroutAPI sharedInstance] zGetVar:@"futureStakeID"];
    NSInteger istakeid = [sstakeid intValue];
    
    NSArray *stakesArr = (NSArray *)[[BaseroutAPI sharedInstance] zGetObj:@"stakesArr"];
    tmp = [stakesArr objectAtIndex:istakeid-1];
    NSString *tmp2 = [tmp objectForKey:@"stakes"];
    NSInteger ii = [tmp2 intValue];
    commitPenalty.text = [NSString stringWithFormat:@"缺勤每次罚金             %2d元", ii];
    
}

- (void)viewDidUnload
{
    [self setCommitDays:nil];
    [self setCommitPenalty:nil];
    [self setThisCommitDays:nil];
    [self setThisCommitPenalty:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - labek delegate

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    UITouch *touch = [touches anyObject];
    NSLog(@"click label tag = %d", touch.view.tag);
    
    if( touch.view.tag == 10 || touch.view.tag == 11)
    {
        actionSheet = [[UIActionSheet alloc] initWithTitle:nil 
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:nil];
        
        [actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
        
        CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
        
        UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
        pickerView.showsSelectionIndicator = YES;
        pickerView.dataSource = self;
        pickerView.delegate = self;
        
        current_tag = touch.view.tag;
        if( touch.view.tag == 10 )
        {
            NSString *scommitid = [[BaseroutAPI sharedInstance] zGetVar:@"selectedCommitID"];
            NSInteger icommitid = [scommitid intValue];
            current_row = icommitid-1;
            [pickerView selectRow:icommitid-1 inComponent:0 animated:NO];
        }
        else
        {
            NSString *sstake = [[BaseroutAPI sharedInstance] zGetVar:@"selectedStakeID"];
            NSInteger istake = [sstake intValue];
            current_row = istake-1;
            [pickerView selectRow:istake-1 inComponent:0 animated:NO];  
        }
        
        [actionSheet addSubview:pickerView];
        
        UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Done"]];
        closeButton.momentary = YES; 
        closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
        closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
        closeButton.tintColor = [UIColor blackColor];
        [closeButton addTarget:self action:@selector(dismissActionSheet) forControlEvents:UIControlEventValueChanged];
        
        [actionSheet addSubview:closeButton];
        [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
        [actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
    }

}

#pragma mark - delegate

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{ //返回列数
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{ //返回每列的最大行数
    if(current_tag == 10)
    {
        //return [daysToGymPerWeekArr count];
        NSArray *commitsArr = (NSArray *)[[BaseroutAPI sharedInstance] zGetObj:@"commitsArr"];
        return [commitsArr count];
    }
    else
    {
        //return [paneltyPerTimeArr count];
        NSArray *stakesArr = (NSArray *)[[BaseroutAPI sharedInstance] zGetObj:@"stakesArr"];
        return [stakesArr count];
    }
}

#pragma mark - datasource

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{ 
    
    if(current_tag == 10)
    {
        NSArray *commitsArr = (NSArray *)[[BaseroutAPI sharedInstance] zGetObj:@"commitsArr"];
        NSDictionary *tmp = [commitsArr objectAtIndex:row];
        NSString *pickerRowTitle = [NSString stringWithFormat:@"每周出勤                     %@天", [tmp objectForKey:@"commits"]];
        return pickerRowTitle;
    }
    else
    {
        //return [paneltyPerTimeArr objectAtIndex:row];
        NSArray *stakesArr = (NSArray *)[[BaseroutAPI sharedInstance] zGetObj:@"stakesArr"];
        NSDictionary *tmp = [stakesArr objectAtIndex:row];
        NSString *pickerRowTitle = [NSString stringWithFormat:@"缺勤每次罚金             %2@元", [tmp objectForKey:@"stakes"]];
        return pickerRowTitle;
    }
}

- (void) updateCommitID:(NSInteger)row{
    NSArray *commitsArr = (NSArray *)[[BaseroutAPI sharedInstance] zGetObj:@"commitsArr"];
    NSDictionary *commit = [commitsArr objectAtIndex:row];
    NSString *scommitDays = [NSString stringWithFormat:@"%@", [commit objectForKey:@"commits"]];
    NSString *commitedID = [NSString stringWithFormat:@"%@", [commit objectForKey:@"id"]];
    
    NSLog(@"row=%d, commitID=%@, commitDays=%@", row, commitedID, scommitDays);
    
    [[BaseroutAPI sharedInstance] zSetVar:@"selectedCommitID" theValue:commitedID];
    [[BaseroutAPI sharedInstance] zSetVar:@"commitNextWeek" theValue:scommitDays];
}

- (void) updateStakeID:(NSInteger)row{
    NSArray *stakesArr = (NSArray *)[[BaseroutAPI sharedInstance] zGetObj:@"stakesArr"];
    NSDictionary *stake = [stakesArr objectAtIndex:row];
    NSString *stakeDollar = [NSString stringWithFormat:@"%@", [stake objectForKey:@"stakes"]];
    NSString *stakeID = [NSString stringWithFormat:@"%@", [stake objectForKey:@"id"]];
    
    NSLog(@"row=%d, stakeID=%@, stakeDollar=%@", row, stakeID, stakeDollar);
    
    [[BaseroutAPI sharedInstance] zSetVar:@"selectedStakeID" theValue:stakeID];
    [[BaseroutAPI sharedInstance] zSetVar:@"stakeNextWeek" theValue:stakeDollar];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{ //选中哪一列哪一行
   
    current_row = row;
    
}

-(void)dismissActionSheet{
    
    
    if(current_tag == 10)
    {
        [self updateCommitID:current_row];
    }
    else
    {
        [self updateStakeID:current_row];
    }
    
    NSMutableDictionary *slist = [[NSMutableDictionary alloc] init];
    [slist setObject:[[BaseroutAPI sharedInstance] zGetVarEx:@"customerid"] forKey:@"cid"];
    [slist setObject:[[BaseroutAPI sharedInstance] zGetVarEx:@"futureCustomerProductId"] forKey:@"customerProductId"];
    [slist setObject:[[BaseroutAPI sharedInstance] zGetVarEx:@"selectedCommitID"] forKey:@"commitNextWeek"];
    [slist setObject:[[BaseroutAPI sharedInstance] zGetVarEx:@"selectedStakeID"] forKey:@"stakeNextWeek"];
    [self zSendServer:slist theTitle:@"请稍等" theCommand:@"/space/update/product"];
    
    
}


#pragma mark - ASIFormDataRequest delegate

- (void)requestFinished:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    if (request.responseStatusCode == 200) {
        
        NSString *responseString = [request responseString];
        NSLog(@"responseString=[%@]", responseString);   
        
        if( [[responseString lowercaseString] isEqualToString:@"success"] )
        {
            //[[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"成功"];
            NSString *stakeid =  [[BaseroutAPI sharedInstance] zGetVarEx:@"selectedStakeID"];
            NSString *commitid =  [[BaseroutAPI sharedInstance] zGetVarEx:@"selectedCommitID"];

            [[BaseroutAPI sharedInstance] zSetVar:@"futureStakeID" theValue:stakeid];
            [[BaseroutAPI sharedInstance] zSetVar:@"futureCommitID" theValue:commitid];
            
            [self UpdateGUIText];
        }
        else
        {
            [[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"失败"]; 
        }
        
    } else {
        NSLog(@"Unexpected error");  
        [[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"通讯失败"];
    }
    
    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
    
}

- (void)requestFailed:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    NSError *error = [request error];
    NSLog(@"Error=%@", error.localizedDescription);   
    
    [[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"通讯失败"];
    
    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}

@end
